<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.ico">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.7.2/css/all.min.css" integrity="sha256-dABdfBfUoC8vJUBOwGVdm8L9qlMWaHTIfXt+7GnZCIo=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"blog.csgrandeur.cn","root":"/","images":"/images","scheme":"Gemini","darkmode":false,"version":"8.22.0","exturl":false,"sidebar":{"position":"left","width_expanded":320,"width_dual_column":240,"display":"post","padding":18,"offset":12},"hljswrap":true,"copycode":{"enable":true,"style":"default"},"fold":{"enable":false,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"duration":200,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"top_n_per_article":1,"unescape":false,"preload":false,"trigger":"auto"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="并查集 普通并查集与带权并查集，快速实现元素集合的合并与查询。">
<meta property="og:type" content="article">
<meta property="og:title" content="29.并查集">
<meta property="og:url" content="http://blog.csgrandeur.cn/2025-04-23-29-%E5%B9%B6%E6%9F%A5%E9%9B%86/index.html">
<meta property="og:site_name" content="CSGrandeur&#39;s Thinking">
<meta property="og:description" content="并查集 普通并查集与带权并查集，快速实现元素集合的合并与查询。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2025-04-23T13:25:34.000Z">
<meta property="article:modified_time" content="2025-04-24T13:55:45.026Z">
<meta property="article:author" content="CSGrandeur">
<meta property="article:tag" content="ACM">
<meta property="article:tag" content="Algorithm">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://blog.csgrandeur.cn/2025-04-23-29-%E5%B9%B6%E6%9F%A5%E9%9B%86/">


<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://blog.csgrandeur.cn/2025-04-23-29-%E5%B9%B6%E6%9F%A5%E9%9B%86/","path":"2025-04-23-29-并查集/","title":"29.并查集"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>29.并查集 | CSGrandeur's Thinking</title>
  

  <script src="/js/third-party/analytics/baidu-analytics.js"></script>
  <script async src="https://hm.baidu.com/hm.js?7958adf931092425a489778560129144"></script>







  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">CSGrandeur's Thinking</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">Cogito Ergo Sum</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
      <div class="search-header">
        <span class="search-icon">
          <i class="fa fa-search"></i>
        </span>
        <div class="search-input-container">
          <input autocomplete="off" autocapitalize="off" maxlength="80"
                placeholder="搜索..." spellcheck="false"
                type="search" class="search-input">
        </div>
        <span class="popup-btn-close" role="button">
          <i class="fa fa-times-circle"></i>
        </span>
      </div>
      <div class="search-result-container">
        <div class="search-result-icon">
          <i class="fa fa-spinner fa-pulse fa-5x"></i>
        </div>
      </div>
    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%B9%B6%E6%9F%A5%E9%9B%86"><span class="nav-number">1.</span> <span class="nav-text">并查集</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%99%AE%E9%80%9A%E5%B9%B6%E6%9F%A5%E9%9B%86"><span class="nav-number">1.1.</span> <span class="nav-text">普通并查集</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B8%A6%E6%9D%83%E5%B9%B6%E6%9F%A5%E9%9B%86"><span class="nav-number">1.2.</span> <span class="nav-text">带权并查集</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BE%8B%E9%A3%9F%E7%89%A9%E9%93%BE"><span class="nav-number">1.2.1.</span> <span class="nav-text">例：食物链</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">CSGrandeur</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">72</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">22</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://blog.csgrandeur.cn/2025-04-23-29-%E5%B9%B6%E6%9F%A5%E9%9B%86/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="CSGrandeur">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="CSGrandeur's Thinking">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="29.并查集 | CSGrandeur's Thinking">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          29.并查集
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2025-04-23 21:25:34" itemprop="dateCreated datePublished" datetime="2025-04-23T21:25:34+08:00">2025-04-23</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2025-04-24 21:55:45" itemprop="dateModified" datetime="2025-04-24T21:55:45+08:00">2025-04-24</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/ACM/" itemprop="url" rel="index"><span itemprop="name">ACM</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/ACM/ACMCOURSE/" itemprop="url" rel="index"><span itemprop="name">ACMCOURSE</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><h1 id="并查集">并查集</h1>
<p>普通并查集与带权并查集，快速实现元素集合的合并与查询。</p>
<span id="more"></span>
<h2 id="普通并查集">普通并查集</h2>
<p>每个集合都有一些点，两个集合之间的任意点连接，则认为两个集合合并</p>
<figure class="highlight txt"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">集合A:    集合B:</span><br><span class="line">  1         5</span><br><span class="line">  |         |</span><br><span class="line">  2         6---8</span><br><span class="line">  |         |</span><br><span class="line">  3         7---9</span><br><span class="line">  |     </span><br><span class="line">  4     </span><br><span class="line"></span><br><span class="line">当2和6相连时，认为集合合并</span><br><span class="line"></span><br><span class="line">  1         5</span><br><span class="line">  |         |</span><br><span class="line">  2 --------6---8</span><br><span class="line">  |         |</span><br><span class="line">  3         7---9</span><br><span class="line">  |     </span><br><span class="line">  4     </span><br></pre></td></tr></table></figure>
<p>此时想知道 <span class="math inline">\(4\)</span> 和 <span
class="math inline">\(8\)</span> 是否在一个集合中，就不得不 DFS
一下，很费时间。</p>
<p>已在同个集合的两点不再连边，则每个集合都可以看作一个树形结构。</p>
<p>并查集通过<strong>路径压缩</strong>树变得"扁平"</p>
<figure class="highlight txt"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">      1             </span><br><span class="line">    /   \           </span><br><span class="line">   2     4               1</span><br><span class="line">  /           ====&gt;   / | | \  </span><br><span class="line">3                    2  3 4  5    </span><br><span class="line">  \                     </span><br><span class="line">    5                   </span><br></pre></td></tr></table></figure>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">Init</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">1</span>; i &lt;= n; i ++) &#123;</span><br><span class="line">        p[i] = i;   <span class="comment">// 初始每个元素自己是一个集合</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 找到 x 所在集合的树的根节点，同时进行路径压缩：</span></span><br><span class="line"><span class="comment">// 即 x 到根 路径上每个点都摘出来重新直接连到根节点上</span></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">fa</span><span class="params">(<span class="type">int</span> x)</span> </span>&#123;<span class="keyword">return</span> p[x] = x == p[x] ? x : <span class="built_in">fa</span>(p[x]);&#125;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">Join</span><span class="params">(<span class="type">int</span> i, <span class="type">int</span> j)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 将 i 与 j 连接，即将它们所在的集合合并为一个</span></span><br><span class="line">    p[<span class="built_in">fa</span>(i)] = <span class="built_in">fa</span>(j);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>int fa(int x) &#123;return p[x] = x == p[x] ? x : fa(p[x]);&#125;</code>
这行代码是并查集的精髓，拆解分析：</p>
<ul>
<li><code>p[x] =</code> 是在为 <code>x</code>
设置父节点，<code>p[x]</code>设为谁，谁就是<code>x</code>的直接父节点</li>
<li><code>x == p[x] ?</code>
三元运算符，如果<code>x</code>自己就是<code>p[x]</code>，说明<code>x</code>是所在集合树的根节点</li>
<li><code>fa(p[x])</code> 如果 <code>x != p[x]</code>，则递归调用
<code>fa(p[x])</code> ，即从 <code>x</code> 父节点继续向上递归找根节点
<ul>
<li>这个递归会返回根节点，从而前面的 <code>p[x] =</code>
赋值就是根节点的编号</li>
<li><code>fa(p[x])</code> 会继续递归处理 <code>x</code> 的父节点
<code>p[x]</code>，那么 <code>p[p[x]]</code>
也会赋值为根节点，<code>p[p[p[[x]]</code>也会……</li>
<li>从而完成路径压缩——<code>x</code>到根的一路的节点都把父节点设为了根节点</li>
</ul></li>
</ul>
<h2 id="带权并查集">带权并查集</h2>
<p>普通并查集的图，边只表示“是同一个集合”。而有一类表达关系的图，“边”带有关系属性。</p>
<h3 id="例食物链">例：食物链</h3>
<p>有 <span class="math inline">\(N\)</span> 个元素，编号为 <span
class="math inline">\(1∼N\)</span>。每个元素属于 <span
class="math inline">\(A\)</span>、<span
class="math inline">\(B\)</span>、<span class="math inline">\(C\)</span>
三种类型之一（比如石头剪刀布），但具体类型未知。</p>
<p>给定 <span class="math inline">\(K\)</span>
条信息，每条信息有两种形式：</p>
<ul>
<li><span class="math inline">\(1\)</span> <span
class="math inline">\(X\)</span> <span
class="math inline">\(Y\)</span>：表示 <span
class="math inline">\(X\)</span> 和 <span
class="math inline">\(Y\)</span> 是同一类型</li>
<li><span class="math inline">\(2\)</span> <span
class="math inline">\(X\)</span> <span
class="math inline">\(Y\)</span>：表示 <span
class="math inline">\(X\)</span> 吃 <span
class="math inline">\(Y\)</span>（<span class="math inline">\(A\)</span>
吃 <span class="math inline">\(B\)</span>，<span
class="math inline">\(B\)</span> 吃 <span
class="math inline">\(C\)</span>，<span class="math inline">\(C\)</span>
吃 <span class="math inline">\(A\)</span>，形成环形）</li>
</ul>
<p>判断这 <span class="math inline">\(K\)</span>
条信息中有多少条是假信息。一条信息在以下情况下为假：</p>
<ul>
<li>与之前的信息冲突（<span class="math inline">\(A\)</span>吃<span
class="math inline">\(B\)</span>，<span
class="math inline">\(B\)</span>吃<span
class="math inline">\(C\)</span>，但<span
class="math inline">\(A\)</span>又吃<span
class="math inline">\(C\)</span>，不符合循环，就是一种冲突）</li>
<li><span class="math inline">\(X\)</span> 或 <span
class="math inline">\(Y\)</span> 大于 <span
class="math inline">\(N\)</span>（出现了不存在的编号）</li>
<li><span class="math inline">\(X\)</span> 吃 <span
class="math inline">\(X\)</span>（自相矛盾）</li>
</ul>
<p>输入：第一行 <span class="math inline">\(N\)</span> <span
class="math inline">\(K\)</span>（<span class="math inline">\(N\)</span>
个元素，<span class="math inline">\(K\)</span> 条信息），接下来 <span
class="math inline">\(K\)</span> 行每行三个整数 <span
class="math inline">\(D\)</span> <span class="math inline">\(X\)</span>
<span class="math inline">\(Y\)</span>（<span
class="math inline">\(D\)</span> 为 <span
class="math inline">\(1\)</span> 或 <span
class="math inline">\(2\)</span>）。</p>
<figure class="highlight txt"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">100 7</span><br><span class="line">1 101 1</span><br><span class="line">2 1 2</span><br><span class="line">2 2 3</span><br><span class="line">2 3 3</span><br><span class="line">1 1 3</span><br><span class="line">2 3 1</span><br><span class="line">1 5 5</span><br></pre></td></tr></table></figure>
<p>输出格式：一行，假信息的数量。</p>
<figure class="highlight txt"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">3</span><br></pre></td></tr></table></figure>
<p>对于石头剪子布，<span class="math inline">\(X\)</span>与<span
class="math inline">\(Y\)</span> 有 3 种边：<span
class="math inline">\(X\)</span> 吃 <span
class="math inline">\(Y\)</span>、<span class="math inline">\(Y\)</span>
吃 <span class="math inline">\(X\)</span>、<span
class="math inline">\(X\)</span>和<span
class="math inline">\(Y\)</span>同类，用集合表示“知道它们两两之间的关系”这个概念，还用这个图来理解：</p>
<figure class="highlight txt"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">集合A:    集合B:</span><br><span class="line">  1         5</span><br><span class="line">  |         |</span><br><span class="line">  2         6---8</span><br><span class="line">  |         |</span><br><span class="line">  3         7---9</span><br><span class="line">  |     </span><br><span class="line">  4     </span><br><span class="line"></span><br><span class="line">当2和6相连时，认为集合合并</span><br><span class="line"></span><br><span class="line">  1         5</span><br><span class="line">  |         |</span><br><span class="line">  2 --------6---8</span><br><span class="line">  |         |</span><br><span class="line">  3         7---9</span><br><span class="line">  |     </span><br><span class="line">  4     </span><br></pre></td></tr></table></figure>
<p><span class="math inline">\(1,2,3,4\)</span> 知道两两相克关系，<span
class="math inline">\(5,6,7,8,9\)</span>
知道两两相克关系，但是两个集合之间相克关系为止。</p>
<p>当某一刻告知了 <span class="math inline">\(2\)</span> 吃 <span
class="math inline">\(6\)</span>，或 <span
class="math inline">\(6\)</span> 吃 <span
class="math inline">\(2\)</span>，或 <span
class="math inline">\(2\)</span> 与 <span
class="math inline">\(6\)</span> 同类，那么<span
class="math inline">\(1\sim 9\)</span>
的两两相克关系就全都能知道了。</p>
<p>这很像并查集的模型，但又不能简单地用父子节点的树来表达。需要让边带权，在路径压缩的时候也要压缩这个权值。</p>
<p><strong>权值定义为：子节点与父节点的“顺时针”距离。</strong></p>
<p>在石头剪子布里，距离就定义为：</p>
<ul>
<li>从石头到剪子、从剪子到布、从布到石头的距离都是 <span
class="math inline">\(1\)</span></li>
<li>从石头到布、从剪子到石头、从布道剪子的距离都是 <span
class="math inline">\(2\)</span>。</li>
</ul>
<p>有这个顺时针距离，就可以确定相克关系。</p>
<p>路径压缩时，仍然是把树“扁平化”，因为维护了任意子节点到父节点的“食物链顺时针”距离，那么就可以压缩出节点到根节点的“食物链顺时针”距离。</p>
<p>用 <span class="math inline">\(A-B\)</span> 表示计算从 <span
class="math inline">\(B\)</span> 出发到 <span
class="math inline">\(A\)</span> 的距离，来演练一下这个合并：</p>
<p>设 <span class="math inline">\(A\)</span>、<span
class="math inline">\(AR\)</span> 是一个集合，<span
class="math inline">\(AR\)</span> 是根节点， <span
class="math inline">\(B\)</span>、<span
class="math inline">\(BR\)</span> 是一个集合，<span
class="math inline">\(BR\)</span> 是根节点。</p>
<figure class="highlight txt"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">    AR     BR</span><br><span class="line">   /        \</span><br><span class="line"> ...         ...</span><br><span class="line"> /            \</span><br><span class="line">A              B</span><br></pre></td></tr></table></figure>
<p>当告知 <span class="math inline">\(A\)</span> 与 <span
class="math inline">\(B\)</span>
的相克关系时，集合合并。先路径压缩，让<span
class="math inline">\(A\)</span>称为<span
class="math inline">\(AR\)</span>的直接子节点，<span
class="math inline">\(B\)</span> 也称为 <span
class="math inline">\(BR\)</span> 的直接子节点</p>
<figure class="highlight txt"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">  AR     BR</span><br><span class="line"> /        \</span><br><span class="line">A           B</span><br></pre></td></tr></table></figure>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">int</span> <span class="title">fa</span><span class="params">(<span class="type">int</span> x)</span> </span>&#123;</span><br><span class="line">    <span class="type">int</span> rt = x == p[x] ? x : <span class="built_in">fa</span>(p[x]);</span><br><span class="line">    d[x] = (d[x] + d[p[x]]) % <span class="number">3</span>;</span><br><span class="line">    p[x] = rt;</span><br><span class="line">    <span class="keyword">return</span> rt;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码中 <code>p[x]</code> 维护 <code>x</code> 的父节点，
<code>d[x]</code> 维护 <code>x</code>到父节点的“食物链顺时针”距离。</p>
<p>当得知 <span class="math inline">\(A\)</span> 与 <span
class="math inline">\(B\)</span> 相克关系时，进行类似合并集合操作，将
<span class="math inline">\(AR\)</span> 作为 <span
class="math inline">\(BR\)</span> 的子节点：</p>
<figure class="highlight txt"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">    BR</span><br><span class="line">   /  \</span><br><span class="line">  AR   B</span><br><span class="line"> /</span><br><span class="line">A</span><br></pre></td></tr></table></figure>
<p>$B-A = (B - BR) + (BR - AR) + (AR-A) $</p>
<p>这里 <span class="math inline">\(AR-A\)</span> 就是代码中的
<code>d[A]</code>，<code>BR-AR</code> 是
<code>d[AR]</code>，<code>BR-B</code>（即<code>-(B-BR)</code>） 是
<code>d[B]</code></p>
<p>因为集合合并是 将 <span class="math inline">\(AR\)</span> 作为 <span
class="math inline">\(BR\)</span> 的子节点，所以在集合合并前后， <span
class="math inline">\(A\)</span>与<span class="math inline">\(B\)</span>
的直接父节点不变（这一刻<span
class="math inline">\(A\)</span>暂且没有进一步路径压缩），从而<code>d[A]</code>、<code>d[B]</code>不变。</p>
<p><code>d[AR]</code>
本来作为根节点是<code>0</code>，合并时只有它会变，要根据 <span
class="math inline">\(A\)</span>与<span class="math inline">\(B\)</span>
的关系，在成为<span class="math inline">\(BR\)</span>
的子节点后发生变化，变换之前的等式得到：</p>
<p><span class="math inline">\((BR-AR) = (BR-B) - (AR-A) +
(B-A)\)</span></p>
<p>对应代码中的
<code>d[AR] = d[B] - d[A] + &lt;A到B的食物链顺时针距离&gt;</code></p>
<ul>
<li>当<span class="math inline">\(A\)</span>与<span
class="math inline">\(B\)</span>是同类，则<span
class="math inline">\(B-A=0\)</span>，即
<code>d[AR]= d[B] - d[A] + 0</code></li>
<li>当 <span class="math inline">\(A\)</span>吃<span
class="math inline">\(B\)</span>，则<span
class="math inline">\(B-A=1\)</span>，<code>d[AR]= d[B] - d[A] + 1</code></li>
</ul>
<p>从而集合基于 <span class="math inline">\(A\)</span> 与 <span
class="math inline">\(B\)</span>
的关系合并，在两个集合各自路径压缩后，只需要 <span
class="math inline">\(2\)</span> 步：</p>
<ol type="1">
<li>把 <span class="math inline">\(AR\)</span> 接到 <span
class="math inline">\(BR\)</span> 作为子节点，就是更新
<code>p[AR]</code></li>
<li>确定 <span class="math inline">\(AR\)</span> 到 <span
class="math inline">\(BR\)</span> 的距离，就是更新
<code>d[AR]</code></li>
</ol>
<p>参考代码</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;cstdio&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;cstdlib&gt;</span></span></span><br><span class="line"><span class="type">const</span> <span class="type">int</span> maxn = <span class="number">5e4</span> + <span class="number">10</span>;</span><br><span class="line"><span class="type">int</span> p[maxn], d[maxn];</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">Init</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>; i &lt; maxn; i++) &#123;</span><br><span class="line">        p[i] = i;</span><br><span class="line">        d[i] = <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">fa</span><span class="params">(<span class="type">int</span> x)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 这里递归了，故p[x]往上已路径压缩</span></span><br><span class="line">    <span class="type">int</span> rt = x == p[x] ? x : <span class="built_in">fa</span>(p[x]);  </span><br><span class="line">    <span class="comment">// 此时 d[p[x]] 已经是 p[x] 到 rt 的距离，那么 x 到 rt 的距离就是 d[x] + d[p[x]]</span></span><br><span class="line">    d[x] = (d[x] + d[p[x]]) % <span class="number">3</span>;</span><br><span class="line">    <span class="comment">// 进行路径压缩，这里和并查集一样，把 x 作为 rt 的直接子节点</span></span><br><span class="line">    p[x] = rt;</span><br><span class="line">    <span class="keyword">return</span> rt;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="type">int</span> N, K, fake = <span class="number">0</span>, op, a, b;</span><br><span class="line">    <span class="built_in">scanf</span>(<span class="string">&quot;%d%d&quot;</span>, &amp;N, &amp;K);</span><br><span class="line">    <span class="built_in">Init</span>();</span><br><span class="line">    <span class="keyword">while</span>(K --) &#123;</span><br><span class="line">        <span class="built_in">scanf</span>(<span class="string">&quot;%d%d%d&quot;</span>, &amp;op, &amp;a, &amp;b);</span><br><span class="line">        <span class="keyword">if</span>(a &gt; N || b &gt; N) &#123;</span><br><span class="line">            fake ++;</span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span>(op == <span class="number">1</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span>(<span class="built_in">fa</span>(a) == <span class="built_in">fa</span>(b) &amp;&amp; d[a] != d[b]) &#123;</span><br><span class="line">                <span class="comment">// 如果已是同一集合但 ab 并不是同类，矛盾</span></span><br><span class="line">                <span class="comment">// fa(a) == fa(b) 已经完成了路径压缩，d[a]和d[b]计算时都已是到同一个父节点的距离</span></span><br><span class="line">                fake ++;</span><br><span class="line">                <span class="keyword">continue</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 此时 a 和 b 都已路径压缩了（在前面的if里）</span></span><br><span class="line">            <span class="comment">// a 祖先 ar 设为 b 祖先的子节点，更新 a 的祖先到 b 的祖先距离 d[ar]</span></span><br><span class="line">            <span class="comment">// 这里 a 和 b 同类，d[ar] 可根据公式推算，</span></span><br><span class="line">            <span class="type">int</span> ar = <span class="built_in">fa</span>(a);    <span class="comment">// 这里要暂存 fa(a)，避免后续合并时重复调用 fa(a) 出现错误</span></span><br><span class="line">            p[ar] = <span class="built_in">fa</span>(b);</span><br><span class="line">            d[ar] = (d[b] - d[a] + <span class="number">3</span>) % <span class="number">3</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">if</span>(<span class="built_in">fa</span>(a) == <span class="built_in">fa</span>(b) &amp;&amp; (d[a] - d[b] + <span class="number">3</span>) % <span class="number">3</span> != <span class="number">1</span>) &#123;</span><br><span class="line">                <span class="comment">// 如果已是同一集合但 a 不吃 b，矛盾</span></span><br><span class="line">                <span class="comment">// a 吃 b 即 a 到 b “食物链顺时针”距离为 1， +3 补足 %3 的同余避免出现负数</span></span><br><span class="line">                <span class="comment">// a 到 b 的距离，即 b - a = (ar - a) - (br - b) = d[a] - d[b]</span></span><br><span class="line">                fake ++;</span><br><span class="line">                <span class="keyword">continue</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 原理同上</span></span><br><span class="line">            <span class="type">int</span> ar = <span class="built_in">fa</span>(a);</span><br><span class="line">            <span class="comment">// 这里 +4 而不是 +1，是补足 %3 的同余避免出现负数，正确计算“食物链顺时针”距离</span></span><br><span class="line">            p[ar] = <span class="built_in">fa</span>(b);</span><br><span class="line">            d[ar] = (d[b] - d[a] + <span class="number">4</span>) % <span class="number">3</span>;  </span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;%d\n&quot;</span>, fake);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/ACM/" rel="tag"># ACM</a>
              <a href="/tags/Algorithm/" rel="tag"># Algorithm</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2025-04-23-28-%E6%90%9C%E7%B4%A2%E5%8A%A0%E9%80%9F%E6%8A%80%E5%B7%A7/" rel="prev" title="28.搜索加速技巧">
                  <i class="fa fa-angle-left"></i> 28.搜索加速技巧
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2025-05-08-30-%E5%9B%BE%E8%AE%BA%E5%9F%BA%E7%A1%801/" rel="next" title="30.图论基础1">
                  30.图论基础1 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments utterances-container"></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 
    <span itemprop="copyrightYear">2025</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">CSGrandeur</span>
  </div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://fastly.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://fastly.jsdelivr.net/npm/@next-theme/pjax@0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/sidebar.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="https://fastly.jsdelivr.net/npm/hexo-generator-searchdb@1.4.1/dist/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>







  




  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://fastly.jsdelivr.net/npm/mathjax@3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>


<script class="next-config" data-name="utterances" type="application/json">{"enable":true,"repo":"CSGrandeur/csgrandeur.github.io","issue_term":"pathname","theme":"github-light"}</script>
<script src="/js/third-party/comments/utterances.js"></script>

</body>
</html>
